package com.hong.concurrent.chapter16;

import java.io.*;
import java.net.Socket;
import java.nio.Buffer;

/**
 * @Author csh
 * @Description 作为接口客户接信息
 * @Date 2018/7/10 21:14
 */
public class ClientHandler implements Runnable {
    /*socket*/
    private final Socket socket;
    /*进行中线程状态*/
    private volatile boolean running = true;

    public ClientHandler(Socket socket) {
        this.socket = socket;
    }


    @Override
    public void run() {
        try (InputStream inputStream = socket.getInputStream();
             OutputStream outputStream=socket.getOutputStream();
             BufferedReader br = new BufferedReader(new  InputStreamReader(inputStream));
             PrintWriter printWriter = new PrintWriter(outputStream)){
            while (running){
                String message = br.readLine();
                if(message==null){
                    break;
                }
                System.out.println("come from client >"+message);
                printWriter.write("echo "+message+"\n");
                /*刷新管道*/
                printWriter.flush();
            }
        } catch (IOException e) {
            this.running = false;
        }finally {
            /*清理动作*/
            this.stop();
        }

    }
    /*关闭*/
    public void stop(){
        if(!running){
            return;
        }
        this.running = false;

        try {
            this.socket.close();
        } catch (IOException e) {
            //

        }
    }
}

